package xyz.xiangyushui.dao.commodity;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import xyz.xiangyushui.dao.Dao;
import xyz.xiangyushui.javaBean.commodity.Commodity;

public class CommodityDao extends Dao{
	public List<Commodity> getAllCommodity(){
		List<Commodity> coms=new LinkedList<>();
		List<Object> list=db.excuteQuery("select id,name,price from commodity ", new Object[]{});
		if(!list.isEmpty()){
			for(Object o:list){
				@SuppressWarnings("unchecked")
				Map<String,Object> m=(Map<String, Object>) o;
				Commodity c=new Commodity();
				c.setId((int) m.get("id"));
				c.setName((String) m.get("name"));
				c.setPrice((double) m.get("price"));
				coms.add(c);
			}
		}
		return coms;
	}
	
	public  List<String> getAllCommodityIdAndName(){
		List<Commodity> coms=getAllCommodity();
		List<String> list=new LinkedList<>();
		coms.forEach(s->{
			list.add(s.getId()+"-"+s.getName());
		});
		return list;
	}
	
	public double totalPrice(String[] commodityIdName){
		double total=0.0;
		for(String s:commodityIdName){
			String[] parts=s.split("-");
			List<Object> list=db.excuteQuery("select price from commodity where id=?", new Object[]{Integer.parseInt(parts[0])});
			if(!list.isEmpty()){
				@SuppressWarnings("unchecked")
				Map<String,Object> m=(Map<String, Object>) list.get(0);
				total+=(double)m.get("price");
			}
		}
		return total;
	}
}
